import { history, useLocation } from '@umijs/max';
import { Tabs } from 'antd';
import React, { useEffect, useState } from 'react';
import routes from '../../../../config/routes';
import './index.less';

interface TabItem {
  key: string;
  label: string;
  closable: boolean;
}

const TabNav: React.FC = () => {
  const location = useLocation();
  const [activeKey, setActiveKey] = useState<string>('');
  const [items, setItems] = useState<TabItem[]>([]);

  // 根据路径查找路由名称
  const findRouteName = (path: string, routeList: any[]): string => {
    for (const route of routeList) {
      if (route.path === path) {
        return route.name || route.path;
      }
      if (route.routes) {
        const name = findRouteName(path, route.routes);
        if (name) return name;
      }
    }
    return '';
  };

  // 添加新标签
  const addTab = (path: string) => {
    const routeName = findRouteName(path, routes);
    if (!routeName) return;

    const newTab: TabItem = {
      key: path,
      label: routeName,
      closable: path !== '/welcome',
    };

    setItems((prev) => {
      if (!prev.find((item) => item.key === path)) {
        return [...prev, newTab];
      }
      return prev;
    });
    setActiveKey(path);
  };

  // 处理标签切换
  const handleTabChange = (key: string) => {
    history.push(key);
  };

  // 处理标签关闭
  const handleTabEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'remove' && typeof targetKey === 'string') {
      const newItems = items.filter((item) => item.key !== targetKey);
      setItems(newItems);

      // 如果关闭的是当前标签，则跳转到最后一个标签
      if (targetKey === activeKey) {
        const lastTab = newItems[newItems.length - 1];
        if (lastTab) {
          history.push(lastTab.key);
        }
      }
    }
  };

  // 监听路由变化
  useEffect(() => {
    if (location.pathname) {
      addTab(location.pathname);
    }
  }, [location.pathname]);

  return (
    <Tabs
      hideAdd
      type="editable-card"
      onChange={handleTabChange}
      activeKey={activeKey}
      onEdit={handleTabEdit}
      items={items}
      className="custom-tab-nav"
    />
  );
};

export default TabNav;
